<template>
  <div class="updgrades">
    <div class="title">
      修改成绩
    </div>
    <div class="elform">
      <el-form ref="query"
               class="form"
               :model="query"
               :rules="rules"
               label-width="60px"
               style="max-width: 580px"
               :rule="rules">
        <el-form-item label="学号"
                      prop="id">
          <el-input v-model="query.id"
                    oninput="value=value.replace(/[^\d]/g,'')" />
        </el-form-item>
        <el-form-item label="数学"
                      prop="matG">
          <el-input v-model="query.matG"
                    oninput="value=value.replace(/[^\d]/g,'')" />
        </el-form-item>
        <el-form-item label="英语"
                      prop="engG">
          <el-input v-model="query.engG"
                    oninput="value=value.replace(/[^\d]/g,'')" />
        </el-form-item>
        <el-form-item label="化学"
                      prop="cheG">
          <el-input v-model="query.cheG"
                    oninput="value=value.replace(/[^\d]/g,'')" />
        </el-form-item>
      </el-form>
    </div>
    <div class="submitdiv">
      <el-button type="primary"
                 size="large"
                 round
                 @click="submit"
                 style="float:left">提交成绩</el-button>
      <el-button type="primary"
                 @click="toIndex"
                 round
                 size="large"
                 style="float:right">回到首页</el-button>
    </div>
    <!-- <el-result
        icon="success"
        title="Success Tip"
        sub-title="Please follow the instructions">
        </el-result> -->
  </div>
</template>

<script>
const checkLen = (rule, value, callback) => {
  var len = value.length
  if (len != 10) {
    callback(new error('请输入正确的学号'))
  } else {
    callback()
  }
};
const checkVal = (rule, value, callback) => {
  if (0 <= value && value <= 150) {
    callback()
  } else {
    callback(new error('请输入正确的分数'))
  }
};
import axios from 'axios';
import { h } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { reject } from 'lodash';
export default {
  name: "updgrades",
  created () {
  },
  data () {
    return {
      query: {
        id: '',
        matG: '',
        engG: '',
        cheG: '',
      },
      rules: {
        id: [{ validator: checkLen, message: "请输入正确的学号(长度18)", trigger: 'blur', required: true }],
        matG: [{ validator: checkVal, message: "请输入正确的成绩(0~150)", trigger: ['blur',] }],
        engG: [{ validator: checkVal, message: "请输入正确的成绩(0~150)", trigger: ['blur',] }],
        cheG: [{ validator: checkVal, message: "请输入正确的成绩(0~150)", trigger: ['blur',] }]
      }
    }
  },
  methods: {
    async judgeNull () {
      var stuid = this.query.id
      return new Promise((resolve, reject) => {
        axios({
          method: 'post',
          url: 'http://localhost:7001/judgrades',
          data: { "Stuid": stuid },
          timeout: 1000,
          headers: { 'Content-Type': 'application/json' },
        }).then(response => {
          var flag = response.data;
          resolve(flag)
        }).catch((error) => {
          reject(error)
        });
      })
    },
    async submit () {
      let ifnull = await this.judgeNull();
      var dates = {
        stuid: this.query.id,
        mathG: this.query.matG,
        englishG: this.query.engG,
        chemistryG: this.query.cheG
      };
      var grades = JSON.stringify(dates);
      //录入信息确认
      ElMessageBox({
        title: '确认录入信息',
        message: h('p', null, [h('i', { style: 'color: teal' }, `${this.query.id}的数学：${this.query.matG}英语：${this.query.engG}化学:${this.query.cheG}`)]),
        showCancelButton: true,
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = 'Loading...'
            if (ifnull) {
              //ifnull为true表示信息确认为空，可以添加数据，发起axios请求传数据
              setTimeout(() => {
                axios({
                  method: 'post',
                  url: 'http://localhost:7001/addgrades',
                  data: grades,
                  timeout: 1000,
                  headers: { 'Content-Type': 'application/json' }
                }).then(response => {
                  alert("数据添加成功")
                  // this.$router.push('/')
                  console.log(response)
                }).catch((error) => {
                  console.log(error)
                })
                done()
                setTimeout(() => {
                  instance.confirmButtonLoading = false
                }, 300)
              }, 7001)
              done()
            } else {
              console.log("数据存在，是否覆盖")
              //执行update
              axios({
                method: 'post',
                url: 'http://localhost:7001/updgrades',
                data: grades,
                timeout: 1000,
                headers: { 'Content-Type': 'application/json' }
              }).then(response => {
                console.log(response)
              }).catch((error) => {
                console.log(error)
              });
              done()
            }
          } else {
            done()
          }
        },
      }).then((action) => {
        ElMessage({
          type: 'info',
          message: `记录修改成功`,
        });
      }).catch((error) => {
        console.log(error)
      })
    },
    toIndex () {
      this.$router.push('/');
    }
  }
}
</script>

<style>
.title {
  margin-top: 50px;
  font-size: 100px;
}
.elform {
  margin-top: 85px;
}
.form {
  margin-left: 30%;
  margin-top: 66px;
}
.submitdiv {
  width: 30%;
  margin: auto;
  margin-top: 85px;
  background-color: aqua;
}
.updgrades {
  background: url("../../../static/img/SelectBGP.png");
  width: 100%;
  height: 100%;
  position: fixed;
  background-size: 100% 100%;
  margin-top: -55px;
}
</style>